package com.huawei.housekeeper.filter;

import com.huawei.saashousekeeper.properties.ResourcesExcluderProperties;
import com.huawei.housekeeper.constants.CommonConstants;
import com.huawei.housekeeper.utils.TokenUtil;
import lombok.extern.log4j.Log4j2;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户信息解析过滤器
 *
 * @author wwx1136431*
 * @since 2022-04-25
 */
@Log4j2
@WebFilter(filterName = "resloveUserInfoFilter", urlPatterns = "/*")
public class ResloveUserInfoFilter implements Filter {

    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    @Autowired
    private ResourcesExcluderProperties ResourcesExcluderProperties;

    @Autowired
    private TokenUtil tokenUtil;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String[] excludedUris = ResourcesExcluderProperties.getExcludedUris();
        for (String uris : excludedUris) {
            if (pathMatcher.match(uris, request.getRequestURI())) {
                log.info("requestUri: " + request.getRequestURI());
                filterChain.doFilter(request, response);
                return;
            }
        }
        try {
            String userName = tokenUtil.getUserNameFromHeader();
            String userId = tokenUtil.getUidFromHeader();
            request.setAttribute(CommonConstants.User.USER_ID, userId);
            request.setAttribute(CommonConstants.User.USER_NAME, userName);

            // 将用户信息加到MDC当中
            MDC.put(CommonConstants.User.USER_NAME, userName);
            MDC.put(CommonConstants.User.USER_ID, userId);
            filterChain.doFilter(request, response);
        } finally {
            MDC.clear();
            // 放入用户username
            request.setAttribute(CommonConstants.User.USER_NAME, null);
            // 放入用户userId
            request.setAttribute(CommonConstants.User.USER_ID, null);
        }
    }
}